/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * frmLogin.java
 *
 * Created on Apr 10, 2010, 5:17:10 PM
 */

package GUI;


import ConnectDB.frmConfig;
import ConnectDB.ConnectDB;
import Interact.Configs;
import Validate_Connect.CheckForm;
import Validate_Connect.DataInteraction;
import Validate_Connect.GUIInteraction;
import java.awt.Color;
import java.awt.Font;
import java.awt.Toolkit;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.UnsupportedLookAndFeelException;

/**
 *
 * @author Shinichi
 */
public class frmLogin extends javax.swing.JFrame {

    /** Creates new form frmLogin */
    @SuppressWarnings("empty-statement")
    public frmLogin() throws ClassNotFoundException, SQLException {
//        ConnectDB.ConnectDatabase();
//        DataInteraction.getConnect();
        Configs.loadConfigurations();
        if(!DataInteraction.connect(Configs.getProperty(Configs.CONFIG_SERVERNAME),
                Configs.getProperty(Configs.CONFIG_PORTNUMBER),
                Configs.getProperty(Configs.CONFIG_SERVERUSERNAME),
                Configs.getProperty(Configs.CONFIG_SERVERPASSWORD),
                Configs.getProperty(Configs.CONFIG_DATABASENAME))) {
            JOptionPane.showMessageDialog(null, "Cannot connect to server");
            frmConfig _frmconfig = new frmConfig();
            _frmconfig.setLocationRelativeTo(null);
            _frmconfig.setVisible(true);
        }
        
        LookAndFeelWindow.LookAndFeelWindow.LookAndFeelWindow();        
        try {
            setIconImage(Toolkit.getDefaultToolkit().getImage(new File("src//Image//login.png").getCanonicalPath()));
        } catch (IOException ex) {
            ex.printStackTrace();
        };
        
        
        
        initComponents();
        getRootPane().setDefaultButton(_btnlogin);
        //read to combo box
        GUIInteraction.readToCombo("select * from tblRoles", _cborole, "RoleName");
//        try {
//            ObjectInputStream fis = new ObjectInputStream(new FileInputStream("info.dat"));
//            Entity.Remembers re=(Remembers) fis.readObject();
//            ResultSet rsper=DataInteraction.queryResultSet("select RoleName from tblRoles where RoleID='"+re.getRole()+"'");
//            String role = null;
//            while(rsper.next())
//                role=rsper.getString("RoleName");
//            _txtusername.setText(re.getUsername());
//            _pwfpassword.setText(re.getPassword());
//            _cborole.setSelectedItem(role);
//            _chkremember.setSelected(re.isCheck());
//        } catch (IOException ex) {
//            Logger.getLogger(frmLogin.class.getName()).log(Level.SEVERE, null, ex);
//        }

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        _lblerr = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        _pwfpassword = new javax.swing.JPasswordField();
        _cborole = new javax.swing.JComboBox();
        _txtusername = new javax.swing.JTextField();
        _btnlogin = new javax.swing.JButton();
        _btnexit = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("AITSM - Login System");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));

        _lblerr.setText("Please enter Username and Password to Logon");

        jLabel4.setText("Password:");

        jLabel3.setText("Username:");

        jLabel5.setText("Roles:");

        _btnlogin.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/system1.png"))); // NOI18N
        _btnlogin.setText("Login");
        _btnlogin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                _btnloginActionPerformed(evt);
            }
        });

        _btnexit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/exit1.png"))); // NOI18N
        _btnexit.setText("Exit");
        _btnexit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                _btnexitActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 24));
        jLabel1.setForeground(new java.awt.Color(51, 51, 255));
        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/login.png"))); // NOI18N
        jLabel1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(116, 116, 116)
                        .add(_lblerr)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED))
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(99, 99, 99)
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jLabel4)
                            .add(jLabel3)
                            .add(jLabel5))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                            .add(_pwfpassword)
                            .add(_cborole, 0, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .add(_txtusername, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 195, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                    .add(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .add(jSeparator1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 454, Short.MAX_VALUE))
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(163, 163, 163)
                        .add(jLabel1))
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(141, 141, 141)
                        .add(_btnlogin)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(_btnexit, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 90, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jLabel1)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jSeparator1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 10, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(16, 16, 16)
                .add(_lblerr)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(_txtusername, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel3))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(_pwfpassword, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel4))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(_cborole, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel5))
                .add(18, 18, 18)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(_btnlogin)
                    .add(_btnexit))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        int i = JOptionPane.showConfirmDialog(null, "Do you want to exit?", "Exit", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        if(i==0)
        {
            System.exit(i);
        }
    }//GEN-LAST:event_formWindowClosing

    private void _btnexitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__btnexitActionPerformed
        int i = JOptionPane.showConfirmDialog(null, "Do you want to exit?", "Exit", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        if(i==0)
        {
            System.exit(i);
        }
    }//GEN-LAST:event__btnexitActionPerformed

    private void _btnloginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__btnloginActionPerformed
        try {
            if (!check()) {
                return;
            }
            String user = _txtusername.getText();
            char[] strpass = _pwfpassword.getPassword();
            String pass = new String(strpass);
            String role = String.valueOf(_cborole.getSelectedItem());
            //get role id
            ResultSet rsper = DataInteraction.queryResultSet("select RoleID from tblRoles where RoleName='" + role + "'");
            String id = null;
            while (rsper.next()) {
                id = rsper.getString("RoleID");
            }
            String sql = "select * from tblUser where Username='" + user + "' and Password='" + pass + "' and RoleID='" + id + "'";
            ResultSet rs = DataInteraction.queryResultSet(sql);
            if (rs.next()) {
                //end
                Interact.Login.set_UserID(rs.getString("UserID"));
                Interact.Login.set_Username(user);
                Interact.Login.set_Password(pass);
                Interact.Login.set_Role(id);
//                if (_chkremember.isSelected() == true) {
//                    try {
//                        ObjectOutputStream fos = new ObjectOutputStream(new FileOutputStream("info.dat"));
//                        Entity.Remembers r = new Remembers(Login.getUsername(), Login.getPassword(), Login.getRole(), true);
//                        fos.writeObject(r);
//                    } catch (Exception ex) {
//                        Logger.getLogger(frmLogin.class.getName()).log(Level.SEVERE, null, ex);
//                    }
//                } else {
//                    try {
//                        ObjectOutputStream fos = new ObjectOutputStream(new FileOutputStream("info.dat"));
//                        Entity.Remembers r = new Remembers("", "", "AD", false);
//                        fos.writeObject(r);
//                    } catch (Exception ex) {
//                        Logger.getLogger(frmLogin.class.getName()).log(Level.SEVERE, null, ex);
//                    }
//                }
                this.dispose();
                frmMain main = new frmMain();
                main.setLocationRelativeTo(null);
                main.setVisible(true);
            } else {
                _lblerr.setForeground(Color.red);
                _lblerr.setFont(new Font("Times New Romal",1,11));
                _lblerr.setText("Login fail!Try again later!");
                _txtusername.requestFocus();
            }
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(frmLogin.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedLookAndFeelException ex) {
            Logger.getLogger(frmLogin.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(frmLogin.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }//GEN-LAST:event__btnloginActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) throws ClassNotFoundException, SQLException {
        frmLogin _frmlogin = new frmLogin();
        _frmlogin.setLocationRelativeTo(null); 
        _frmlogin.setVisible(true);
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton _btnexit;
    private javax.swing.JButton _btnlogin;
    private javax.swing.JComboBox _cborole;
    private javax.swing.JLabel _lblerr;
    private javax.swing.JPasswordField _pwfpassword;
    private javax.swing.JTextField _txtusername;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JSeparator jSeparator1;
    // End of variables declaration//GEN-END:variables

    private boolean check()
    {
        String _username = _txtusername.getText();
        char[] _chrpass = _pwfpassword.getPassword();
        String _password = new String(_chrpass);
        if(!CheckForm.isPwdUsername(_username))
        {
            _lblerr.setText("Please Enter Username");
            _lblerr.setForeground(Color.red);
            _lblerr.setFont(new Font("Times New Romal",1,11));
            _txtusername.requestFocus();
            return false;
        }
        if(!CheckForm.isPwdUsername(_password))
        {
            _lblerr.setText("Please Enter Password");
            _lblerr.setForeground(Color.red);
            _lblerr.setFont(new Font("Times New Romal",1,11));
            _pwfpassword.requestFocus();
            return false;
        }
        return true;
    }
}
